package com.googlecode.gwt.test.plugin.resourcesListner;


import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;

import com.googlecode.gwt.test.plugin.editors.GWTCsvConfiguration;
import com.googlecode.gwt.test.plugin.editors.KeyWords;
import com.googlecode.gwt.test.plugin.util.GwtCsvTestType;

public class JavaCustomKeyWordsAnalyser implements IResourceChangeListener {

	KeyWords keyWords;

	IProject currentProject;

	GWTCsvConfiguration configuration;

	private MacroChangeListner macroChangeListner;

	public JavaCustomKeyWordsAnalyser(KeyWords keyWords, IProject currentProject, GWTCsvConfiguration configuration,
			MacroChangeListner macroChangeListner) {
		super();
		this.currentProject = currentProject;
		this.keyWords = keyWords;
		this.configuration = configuration;
		this.macroChangeListner = macroChangeListner;
		this.compute();

	}

	@Override
	public void resourceChanged(IResourceChangeEvent event) {
		if (event.getType() != IResourceChangeEvent.POST_CHANGE) {
			return;
		}
		try {
			event.getDelta().accept(new IResourceDeltaVisitor() {
				public boolean visit(IResourceDelta delta) {
					IResource res = delta.getResource();
					switch (delta.getKind()) {
					case IResourceDelta.ADDED:
						if (res.getType() == IResource.FILE && "java".equals(res.getFileExtension()) && isGwtCsvTest(res)) {
							macroChangeListner.clean();
							macroChangeListner.compute();
						}
					case IResourceDelta.CHANGED:
						if (res.getType() == IResource.FILE && "java".equals(res.getFileExtension()) && isGwtCsvTest(res)) {
							compute();
						}
						break;
					}
					return true; // visit the children
				}
			});
		} catch (CoreException e) {
			e.printStackTrace();
		}

	}

	private void compute() {
		keyWords.refresh();
		configuration.getScanner().update();
	}

	private boolean isGwtCsvTest(IResource res) {
		try {
			IJavaElement jProject = JavaCore.create(res);
			if (jProject instanceof ICompilationUnit) {
				ICompilationUnit u = (ICompilationUnit) jProject;
				ITypeHierarchy hierarchy = u.getTypes()[0].newTypeHierarchy(null);
				IType clazz = GwtCsvTestType.getGwtCsvTestType(currentProject);
				return hierarchy.contains(clazz);
			}
		} catch (Exception e) {
		}
		return false;
	}

}
